import matplotlib.pyplot as plt
import numpy as np

# 设置支持 Unicode 的字体
plt.rcParams['font.sans-serif'] = ['Microsoft YaHei','DejaVu Sans']
plt.rcParams['axes.unicode_minus'] = False

# 连续性的ε-δ演示
def demonstrate_continuity():
    # 示例函数：f(x) = x^2 在 x=2 处的连续性
    def f(x):
        return x**2
    
    x0 = 2
    f_x0 = f(x0)
    epsilon = 0.5
    
    # 计算对应的delta
    # 对于f(x)=x^2，|f(x)-f(2)| = |x^2-4| = |x-2||x+2|
    # 当|x-2|<1时，|x+2|<5，所以取delta = min(1, epsilon/5)
    delta = min(1, epsilon/5)
    
    x_values = np.linspace(x0 - 2*delta, x0 + 2*delta, 100)
    y_values = f(x_values)
    
    plt.figure(figsize=(10, 6))
    plt.plot(x_values, y_values, 'b-', linewidth=2, label='f(x) = x²')
    plt.axvline(x=x0, color='r', linestyle='--', alpha=0.7, label=f'x_0 = {x0}')
    plt.axhline(y=f_x0, color='r', linestyle='--', alpha=0.7, label=f'f(x_0) = {f_x0}')
    
    # 显示ε区间
    plt.axhline(y=f_x0 + epsilon, color='g', linestyle=':', alpha=0.5, label='ε区间')
    plt.axhline(y=f_x0 - epsilon, color='g', linestyle=':', alpha=0.5)
    plt.fill_between(x_values, f_x0 - epsilon, f_x0 + epsilon, alpha=0.1, color='green')
    
    # 显示δ区间
    plt.axvline(x=x0 + delta, color='orange', linestyle=':', alpha=0.5, label='δ区间')
    plt.axvline(x=x0 - delta, color='orange', linestyle=':', alpha=0.5)
    plt.fill_betweenx(y_values, x0 - delta, x0 + delta, alpha=0.1, color='orange')
    
    plt.scatter([x0], [f_x0], color='red', s=50, zorder=5)
    plt.title('函数连续性演示: ε-δ定义')
    plt.xlabel('x')
    plt.ylabel('f(x)')
    plt.legend()
    plt.grid(True, alpha=0.3)
    plt.show()
    
    print(f"对于 ε = {epsilon}, 找到 δ = {delta:.3f}")
    print(f"当 |x - {x0}| < {delta:.3f} 时，|f(x) - {f_x0}| < {epsilon}")

demonstrate_continuity()
